<template>
  <div class="container"  style="white-space: nowrap; height: 200px;">
    <div class="card text-center">
    <div class="card-body">
      <h5 class="card-title">用户信息</h5>
      <div class="table-responsive">
        <table class="table">
          <thead>
            <tr>
              <th scope="col">用户</th>
              <th scope="col">客户端设置</th>
              <th scope="col">数据集设置</th>
              <th scope="col">模型状态</th>
              <th scope="col">验证结果</th>
              <th scope="col">追踪</th>
              <th scope="col">追踪结果</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(user, index) in Localuser" :key="index">
              <td>{{ user.name }}</td>
              <td>
                <select v-model="user.setting"  class="form-select">
                  <option v-for="(option, optionIndex) in settingOptions" :key="optionIndex">{{ option }}</option>
                </select>
              </td>
              <td>
                <select v-model="user.dataset"  class="form-select">
                  <option v-for="(option, optionIndex) in settingData" :key="optionIndex">{{ option }}</option>
                </select>
              </td>
              <td>{{ user.status }}</td>
              <td>{{ user.result1 }}</td>
              <td>
                <button class="btn btn-primary" @click="startProcess(user,index)">请求追踪</button>
              </td>
              <td>{{ user.result2 }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
  </div>
  <!-- 按钮 -->
<div class="container mt-6"  style="white-space: nowrap; height: 200px;">
  <div class="card mt-4 text-center">
    <div class="card-body">
      <div class="row mt-2 mb-2">
        <div class="col">
          <button class="btn btn-primary btn-lg" style="width: 100%; height: 100%" @click="handleButtonClick(1)">开始训练</button>
        </div>

        <div class="col">
          <button class="btn btn-primary btn-lg" style="width: 100%; height: 100%" @click="handleButtonClick(2)">上传模型</button>
        </div>
        <div class="col">
          <button class="btn btn-primary btn-lg" style="width: 100%; height: 100%" @click="handleButtonClick(3)">接收模型</button>
        </div>
        <div class="col">
          <button class="btn btn-primary btn-lg" style="width: 100%; height: 100%" @click="handleButtonClick(4)">验证模型</button>
        </div>
      </div>
    </div>
  </div>
</div>
</template>

<script setup>
import {ref, onMounted, onUnmounted} from 'vue'
import { v4 as uuidv4 } from 'uuid'
import axios from 'axios'
import {useStore} from "vuex";
import {ClientInitialEventBus, HomeeventBus, TraceserverEventBus} from "@/views/event-bus";


const clientId = ref(null)
const clientid = ref(null)
const serverResponse = ref(null)
let isPageClosing = false // 添加标志以跟踪页面状态

const initialUser = [
  {name: 'user1', setting: '默认设置', dataset:'数据集一',status: '未训练', result1: '未验证', result2: ''},
];

const Localuser = ref([]);
const settingOptions = ['默认设置', '伪造hash', '伪造签名1', '伪造签名2'];
const settingData = ['数据集一', '数据集二', '数据集三'];
// Access the Vuex store
const store = useStore();
const hideSidebar = () => store.commit('hideSidebar');
const showSidebar = () => store.commit('showSidebar');
const loadUsersFromSessionStorage = () => {
  try {
    const storedUser = JSON.parse(sessionStorage.getItem('local_user'));
    if (storedUser && Array.isArray(storedUser)) {
      Localuser.value = storedUser;
    } else {
      Localuser.value = [...initialUser];
    }
  } catch (error) {
    console.error('Error loading users from sessionStorage:', error);
    Localuser.value = [...initialUser];
  }
};

// 将用户设置保存到本地存储
const saveUsersToSessionStorage = () => {
  try {
    sessionStorage.setItem('local_user', JSON.stringify(Localuser.value));
  } catch (error) {
    console.error('Error saving users to sessionStorage:', error);
  }
};
// 检查 sessionStorage 中是否已经存在客户端ID，如果不存在则生成一个新的UUID作为客户端ID
onMounted(() => {
  hideSidebar();
  loadUsersFromSessionStorage()
  const storedClientId = sessionStorage.getItem('clientId')
  const storedClientid = sessionStorage.getItem('client_id')

  if (storedClientId) {
    clientId.value = storedClientId
    clientid.value = storedClientid
    sendClientIdToBackend(storedClientId,storedClientid)
    console.log('clientid',clientid.value)
  } else {
    const newClientId = uuidv4()
    clientId.value = newClientId
    sessionStorage.setItem('clientId', newClientId)
    // 将新生成的客户端ID发送给后端
    sendClientIdToBackend(newClientId,'null')
  }
})

onUnmounted(() => {
  showSidebar();
  saveUsersToSessionStorage()
});
// 设置值转换函数
const convertSettingToNumber  = (setting) => {
  switch (setting) {
    case '默认设置':
      return 0;
    case '伪造hash':
      return 1;
    case '伪造签名1':
      return 2;
    case '伪造签名2':
      return 3;
    default:
      return -1; // 或其他合适的默认值
  }
};
const convertDatasetToNumber  = (dataset) => {
  switch (dataset) {
    case '数据集一':
      return 1;
    case '数据集二':
      return 2;
    case '数据集三':
      return 3;
    default:
      return -1; // 或其他合适的默认值
  }
};

// 将生成的客户端ID发送给后端
const sendClientIdToBackend = async (client_ID,client_id) => {
  try {
    const headers = {
      'Content-Type': 'application/json', // 设置请求的 Content-Type
      'Authorization': 'Bearer <token>', // 设置授权头信息
      'X-Custom-Header': 'value' // 添加自定义头信息
    };
    const response = await axios.post(`${process.env.VUE_APP_BACKEND_API}/local`, { client_ID,client_id ,task:"client_id"}, { headers });
    // 处理后端返回的信息
    serverResponse.value = response.data.client_id;
    sessionStorage.setItem('client_id', serverResponse.value)
    clientid.value = sessionStorage.getItem('client_id')
    console.log('response',serverResponse.value)

  } catch (error) {
    console.error('Failed to send client ID to backend:', error);
    serverResponse.value = 'Failed to send client ID to backend';

  }
}

// 在页面关闭时，通知后端删除客户端ID
window.addEventListener('beforeunload', (event) => {
  // 如果页面不是持久化的（即不是从浏览器缓存恢复的），且页面不是正在关闭的状态，则发送删除请求
  if (!event.persisted && !isPageClosing) {
    deleteClientIdFromBackend()
  }
})

// 在页面关闭时将标志设置为 true
window.addEventListener('unload', () => {
  isPageClosing = true
})

const deleteClientIdFromBackend = () => {
  const storedClientId = sessionStorage.getItem('clientId')
  const storedClientid = sessionStorage.getItem('client_id')
  if (storedClientId) {
    const url = `${process.env.VUE_APP_BACKEND_API}/local`
    const data = JSON.stringify({clientId: storedClientId,clientid: storedClientid,task:"delete_client_id"})
    const headers = {
      'Content-Type': 'application/json', // 设置请求的 Content-Type
      'Authorization': 'Bearer <token>', // 设置授权头信息
      'X-Custom-Header': 'value' // 添加自定义头信息
    };
    navigator.sendBeacon(url, new Blob([data], headers))
  }
}

//限制按钮在未响应前点击
const isProcessing = ref(false);
const startProcess = async (user,index) => {
  if (isProcessing.value) {
    alert('请求正在处理中...');
    return;
  }
  isProcessing.value = true;
  user.result2 = '处理中...';
  console.log('index', index);
  try {
    const response = await axios.post(`${process.env.VUE_APP_BACKEND_API}/Client`, {
      task:"trace_request",
      idx: index
    });

    if (response.status === 200) {
      // 触发更新事件并传递更新的 idx 数据
      const idx = response.data.request_id
      TraceserverEventBus.value.dispatchEvent(new CustomEvent('trace_request', { detail: idx }));
      console.log('按钮',index,'的响应:', response.data);
    }
  } catch (error) {
    console.error('请求失败:', error);
  } finally {
    isProcessing.value = false;
  }
};
//限制按钮在未响应前点击
let isButtonClicked = false;
const handleButtonClick = async (buttonNumber) => {
  try {
    // 检查按钮是否已经被点击，如果是，则直接返回
    if (isButtonClicked) {
      alert('正在等待上一次请求的响应，请稍后...');
      console.log('按钮已经被点击，正在等待上一次请求的响应...');
      return;
    }
    // 按钮被点击，设置状态为 true
    isButtonClicked = true;
    let response;
    // const notDefaultSettingsIndices = [];
    let settings = [];
    let datasets = [];
    switch (buttonNumber) {
      case 1:
        //初始化前端页面
        Localuser.value.forEach(user => {user.status = '未训练';user.result1 = '未验证';user.result2=''});
        saveUsersToSessionStorage();
        ClientInitialEventBus.value.dispatchEvent(new CustomEvent('initializePages'));
        try {
          // 统计所有用户的setting值，并向后端发送请求
          settings = Localuser.value.map(user => convertSettingToNumber(user.setting));
          datasets = Localuser.value.map(user => convertDatasetToNumber(user.dataset));
          response = await axios.post(`${process.env.VUE_APP_BACKEND_API}/Client`, {task:"local_train", local_settings: settings,local_datasets:datasets });
          if (response.status === 200) {
           // 获取 users 中的 setting 数据
            const updatedSettings = Localuser.value.map(user => user.setting);
            console.log('updatedSettings:', updatedSettings);
            // 触发更新事件并传递更新的 setting 数据
            HomeeventBus.value.dispatchEvent(new CustomEvent('updateClients', { detail: updatedSettings }));
            // 点击按钮1后，将所有用户的状态设置为B
            Localuser.value.forEach(user => {user.status = '待上传';});
            saveUsersToSessionStorage();
            }
          console.log('提交成功:', settings);
          console.log('提交成功:', response.data);
          console.log('Settings sent successfully:', response.data);
        } catch (error) {
          console.error('Error sending settings:', error);
        }
        break;

      case 2:
        try {
          response = await axios.post(`${process.env.VUE_APP_BACKEND_API}/Client`,{task:"post_model"});

          if (response.status === 200) {
           // 点击按钮2后，将所有用户的状态设置为C
            Localuser.value.forEach(user => {user.status = '已上传';});
            saveUsersToSessionStorage();
            console.log('按钮2的响应:', response.data);
          } else{
            console.error('响应失败');
          }
        } catch (error) {

          console.error('请求失败:', error);
        }
        break;
      case 3:
        try {
          response = await axios.post(`${process.env.VUE_APP_BACKEND_API}/Client`,{task:"client_receive_model"});
          if (response.status === 200) {
           // 点击按钮3后，将所有用户的状态设置为D
            Localuser.value.forEach(user => {user.status = '已接收';});
            saveUsersToSessionStorage();
            console.log('按钮3的响应:', response.data);
          } else{
            console.error('响应失败');
          }
        } catch (error) {
          console.error('请求失败:', error);
        }
        break;
      case 4:
        try {
          response = await axios.post(`${process.env.VUE_APP_BACKEND_API}/Client`,{task:"client_verify"});
          if (response.status === 200) {
            const updatedArray = response.data;
            // 根据返回的数组更新 users 中的 result1
            Localuser.value = saveUsersToSessionStorage.value.map((user, index) => ({
              ...user,
              result1: updatedArray[index] ? '验证成功' : '验证失败'
            }));
            console.log('按钮4的响应:', response.data);
          } else{
            console.error('响应失败');
          }
        } catch (error) {
          console.error('请求失败:', error);
        }
        break;
      default:
        console.error('未知的按钮编号:', buttonNumber);
        break;
    }
    // 请求完成后，设置状态为 false，允许下一次点击
    isButtonClicked = false;
  } catch (error) {
    console.error('请求失败:', error);
    // 请求完成后，设置状态为 false，允许下一次点击
    isButtonClicked = false;
  }
};

</script>
// 在此之后，你可以根据需要修改 serverState 的值，以更新背景颜色和文本
<style scoped>
.bg-primary-light {
  background-color: #152ca8 !important; /* 淡蓝色 */
}

.bg-danger-light {
  background-color: #a12004 !important; /* 淡灰色 */
}
.btn-secondary.disabled {
  pointer-events: none;
  opacity: 1;
}
.disabled1 {
  pointer-events: none;
  opacity: 1;
}
</style>